package com.leonzx.base.service.system;

import com.leonzx.base.dao.system.BaseFileDAO;
import com.leonzx.base.entity.system.BaseFile;
import com.leonzx.base.service.BaseService;
import com.leonzx.base.service.file.FileUploadService;
import com.leonzx.base.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;

/**
 * @Author:chen
 * @Description:
 * @Date: 2018-07-10 12:05
 */
@Service
public class BaseFileService extends BaseService {

    @Autowired
    private BaseFileDAO baseFileDAO;
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 保存附件表
     *
     * @Author chen
     * @Date 2018/7/12 10:18
     */
    public BaseFile saveBaseFile(String newFileName, String oldFileName, String serviceFilePath, String userId, String qz, String savePath, String type) {
        String filePath = "http://" + OSSConstants.bucketName + "." + OSSConstants.endpoint + "/" + qz.replaceAll("\\\\", "/") + "/" + savePath + "/" + newFileName;
        BaseFile baseFile = new BaseFile();
        baseFile.setId(UUIDUtils.getUUID());
        baseFile.setCreateTime(new Date());
        baseFile.setCreateUserId(userId);
        baseFile.setNewFileName(newFileName);
        baseFile.setOldFileName(oldFileName);
        baseFile.setFilePath(filePath);
        baseFile.setType(type);
        baseFile.setServiceFilePath(serviceFilePath);
        baseFileDAO.insert(baseFile);
        return baseFile;
    }

    /**
     * 删除oss文件及服务器文件夹
     *
     * @Author chen
     * @Date 2018/7/12 10:17
     */
    @Transactional
    public void delBaseFile(String id, HttpServletRequest request, HttpServletResponse response) {
        BaseFile baseFile = baseFileDAO.findById(id);
        delOSSFile(baseFile);
        delServiceFile(baseFile, request, response);
    }

    public void delOSSFile(BaseFile baseFile) {
        //删除oss上的文件
        String path = Constants.FILE_QZ + File.separator + Constants.FILE_TYPE_EMAIL_FILE;
        fileUploadService.delete(path + File.separator + baseFile.getNewFileName());
    }

    public void delServiceFile(BaseFile baseFile, HttpServletRequest request, HttpServletResponse response) {
        //删除服务器上的文件
        String newFileName = baseFile.getNewFileName();
        String[] nameAndType = newFileName.split("\\.");
        String filePath = request.getSession().getServletContext().getRealPath(Constants.FILE_QZ + File.separator + Constants.FILE_TYPE_EMAIL_FILE + File.separator + nameAndType[0]);
        File file = new File(filePath);
        FileUtils.deleteAllFilesOfDir(file);
    }


}
